package DataProcess;

import baseAPI.*;
import baseClass.Admin;
import baseClass.Room;
import baseClass.RoomTable;
import baseClass.ServiceTable;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.effect.DropShadow;
import javafx.scene.image.Image;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.stage.Modality;
import javafx.stage.Stage;

import javax.print.DocFlavor;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

public class ServicePage {
    private static MyServer server;
    private static Database database;
    private static RadioButton radioWakeUp, radioClean;
    private static TableView<ServiceTable> tableView = new TableView<>();
    private static TableColumn<ServiceTable, String> tcRoomNumber, tcService, tcNote;
    private static Button btnHandle, btnSend;
    private static Pane pane;
    private static ServiceTable serviceToHandle;

    public static void bind(Parent service, Database database, MyServer server){
        ServicePage.server = server;//服务器初始化
        ServicePage.database = database;//数据库初始化

        //控件绑定
        radioWakeUp = (RadioButton)service.lookup("#radioWakeUp");
        radioClean = (RadioButton)service.lookup("#radioClean");
        btnHandle = (Button)service.lookup("#btnHandle");
        btnSend = (Button)service.lookup("#btnSend");
        pane = (Pane)service.lookup("#pane");

        //radioButton设置为一组
        ToggleGroup toggleGroup = new ToggleGroup();
        radioWakeUp.setToggleGroup(toggleGroup);
        radioClean.setToggleGroup(toggleGroup);
        radioWakeUp.setSelected(true);

        //设置tableView
        pane.getChildren().add(tableView);
        tableView.setPrefWidth(1082);
        tableView.setPrefHeight(664);
        tableView.setLayoutX(24);
        tableView.setLayoutY(142);
        tableView.setEditable(false);

        tcRoomNumber = new TableColumn<>("房号");
        tcService = new TableColumn<>("请求类型");
        tcNote = new TableColumn<>("备注");

        tcRoomNumber.setCellValueFactory(new PropertyValueFactory<ServiceTable, String>("roomNumber"));
        tcService.setCellValueFactory(new PropertyValueFactory<ServiceTable, String>("service"));
        tcNote.setCellValueFactory(new PropertyValueFactory<ServiceTable, String>("note"));

        tableView.getColumns().addAll(tcRoomNumber, tcService, tcNote);
        tableView.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);

        tableView.getSelectionModel().selectedItemProperty().addListener(//选中某一行后绑定要处理的对象
                new ChangeListener<ServiceTable>() {
                    @Override
                    public void changed(
                            ObservableValue<? extends ServiceTable> observableValue,
                            ServiceTable oldItem, ServiceTable newItem) {
                            serviceToHandle = newItem;//更新选中对象
                    }
                });

        btnHandle.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                handleRequest();//处理客户请求
            }
        });

        radioWakeUp.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                updateTable(ServiceTable.WAKE_UP);
            }
        });

        radioClean.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                updateTable(ServiceTable.CLEAN);
            }
        });

        btnSend.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                send();
            }
        });
    }

    public static void updateService(Parent service){
        updateTable(ServiceTable.WAKE_UP);
    }

    public static void handleRequest(){
        if(serviceToHandle == null){
            AlertStage.show("提示", "请先选择要处理的请求！");
            return;
        }

        serviceToHandle.setHandled(database);
        server.chooseClient(Integer.parseInt(serviceToHandle.getRoomNumber()));

        if(radioWakeUp.isSelected()){
            server.sendMessage("wakeUpHandled" + "||" + serviceToHandle.getNote());
            updateTable(ServiceTable.WAKE_UP);
        }
        else if(radioClean.isSelected()){
            server.sendMessage("cleanHandled");
            updateTable(ServiceTable.CLEAN);
        }
    }

    private static void updateTable(int service){
        ObservableList<ServiceTable> services = ServiceTable.getServiceTable(database, service);

        if(services == null){//清空
            tableView.getItems().clear();
        }
        else{//刷新
            tableView.setItems(services);
        }
    }

    public static void send(){
        ObservableList<RoomTable> rooms = FXCollections.observableArrayList();
        rooms.addAll(RoomTable.getRoomTable(Room.getThroughRoomStatus(0,database)));//获取已入住的房间列表

        //显示房间列表
        TableView<RoomTable> roomTableView = new TableView<>();
        TableColumn<RoomTable, CheckBox> tcSelected = new TableColumn<>("多选");
        TableColumn<RoomTable, String> tcRoomNumber = new TableColumn<>("已入住的房间");
        tcSelected.setCellValueFactory(new PropertyValueFactory<>("checkBox"));
        tcRoomNumber.setCellValueFactory(new PropertyValueFactory<>("roomNumber"));
        roomTableView.getColumns().addAll(tcSelected, tcRoomNumber);
        roomTableView.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
        roomTableView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);//可以多选
        roomTableView.setItems(rooms);
        roomTableView.setStyle("-fx-pref-width: 250;-fx-pref-height: 210;");
        roomTableView.setLayoutX(100);
        roomTableView.setLayoutY(150);

        Stage stage = new Stage();
        stage.initModality(Modality.APPLICATION_MODAL);
        stage.getIcons().add(new Image("/pic/ico.png"));
        stage.setTitle("发送信息");
        stage.setResizable(false);
        stage.setWidth(400);
        stage.setHeight(835);

        TextArea messageField = new TextArea();
        Button check = new Button();

        DropShadow dropShadow = new DropShadow();
        dropShadow.setOffsetY(1.0);
        dropShadow.setOffsetX(1.0);
        dropShadow.setColor(Color.rgb(129,192,212));
        dropShadow.setSpread(0.2);

        messageField.setLayoutX(100);
        messageField.setLayoutY(380);
        messageField.setPrefWidth(250);
        messageField.setPrefHeight(180);
        messageField.setStyle(
                "    -fx-text-fill:black;\n" +
                        "    -fx-font-size: 13pt;\n" +
                        "    -fx-opacity: 0.7;\n" +
                        "    -fx-font-family: \"MV Boli\";\n" +
                        "    -fx-font-weight: bold;\n" +
                        "    -fx-border-radius: 15px;\n" +
                        "    -fx-background-radius: 15px;\n" +
                        "    -fx-background-insets: 0;\n" +
                        "    -fx-background-color: transparent,rgb(20,23,34),transparent,rgb(20,23,34);");
        messageField.setEffect(dropShadow);
        messageField.setWrapText(true);
        messageField.setPrefRowCount(10);


        check.setLayoutX(170);
        check.setLayoutY(580);
        check.setPrefWidth(60);
        check.setPrefHeight(60);
        check.setStyle("-fx-background-image:url(/pic/check.png);-fx-background-color: transparent;");

        check.setOnMouseEntered(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent event) {
                Animation.checkButton(check);
            }
        });
        check.setOnMouseExited(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent event) {
                Animation.resetCheck(check);
            }
        });
        check.setOnMousePressed(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent event) {
                Animation.checked(check);
            }
        });
        check.setOnMouseReleased(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent event) {
                Animation.reset1(check);
            }
        });

        check.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                ObservableList<Integer> roomNumbers = FXCollections.observableArrayList();
                ObservableList<RoomTable> rooms = roomTableView.getItems();

                for(int i=0;i<rooms.size();i++){
                    if(rooms.get(i).getCheckBox().isSelected()){
                        roomNumbers.add(Integer.parseInt(rooms.get(i).getRoomNumber()));
                    }
                }

                server.chooseClient(roomNumbers);
                server.sendMessage("message" + "||" + messageField.getText());
            }
        });

        Pane pane = new Pane(roomTableView, messageField, check);
        pane.setStyle("-fx-background-image: url(/pic/Send.png)");
        Scene scene = new Scene(pane);
        stage.setScene(scene);
        stage.show();
    }

    public static void inComingRequest(String[] message){
        if(message.length == 4){//早晨叫醒和清洁服务
            database.insert("service", message[1] + "," + message[2] + "," + "\"" + message[3] +"\"");
        }
        else{//点餐服务
            database.insert("service", message[1] + "," + message[2] + "," + "\"" + message[3] + "||" + message[4] +"\"");
        }

        //发送回执
        server.chooseClient(Integer.parseInt(message[1]));
        server.sendMessage("requestReceived");

        if(radioWakeUp.isSelected() && Integer.parseInt(message[2]) == 1){
            updateTable(ServiceTable.WAKE_UP);
        }
        else if(radioClean.isSelected() && Integer.parseInt(message[2]) == 2){
            updateTable(ServiceTable.CLEAN);
        }
        else if(Integer.parseInt(message[2]) == 3){//交给厨师端处理
            //账单更新
            database.insert("bill", message[1] + "," + "\"" + message[3] + "\"" + "," + "localtime()" + "," + message[5] + ", 1");

            //交给厨师端处理
            server.chooseClient(-1);
            server.sendMessage("order" + "||" + message[1] + "||" + message[3] + "||" + message[4]);
        }
    }

    public static void sendDishes(String roomNumber){
        ResultSet resultSet = database.select("*", "dish");
        server.chooseClient(Integer.parseInt(roomNumber));
        server.sendMessage("clearDishes");
        try{
            while(resultSet.next()){
                server.chooseClient(Integer.parseInt(roomNumber));
                server.sendMessage("addDish" + "||" + resultSet.getString(1) + "||" + resultSet.getDouble(2));
            }
        }catch (SQLException ex){
            System.out.println("sendDishesException");
        }
    }

    public static void sendFoodFinished(String roomNumber){
        database.delete("service", "roomNumber = " + roomNumber + " and service = 3");
        server.chooseClient(Integer.parseInt(roomNumber));
        server.sendMessage("orderFinished");
    }

    public static void sendOrders(){//获取未完成的订单
        ResultSet resultSet = database.select("roomNumber, note", "service", "service = 3");
        try{
            while(resultSet.next()){
                server.chooseClient(-1);
                server.sendMessage("order" + "||" + resultSet.getInt(1) + "||" + resultSet.getString(2) );
            }
        }catch (SQLException ex){
            System.out.println("sendOrdersException");
        }
    }

    public static MyServer getServer(){
        return server;
    }
}
